<?php
namespace app\web\controller;

use app\model\Theme; 

class Fanpaichoujiang extends Base
{
    public function Fanpaichoujiang()
    {
global $_G, $_P;
$system = $_G['system'];
$_G['page']['title'] = '参团列表 - ' . $system['sysname'];
//load_func('tpl');
$GLOBALS['frames'] = array();
$themeid = intval($_P['themeid']);
if($themeid <= 0){
	$themeid = Theme::getDefaultThemenew();
}
$theme = Theme::getThemeById($themeid);
if(empty($theme['id'])){
	return_msg('还没有创建活动,请联系管理员');
}
$config = 	Theme::getConfig($themeid);
$theme = Theme::getThemeById($themeid);
$id = intval($_P['id']);
$uid = intval($_P['uid']);
$giftid = intval($_P['giftid']);
$do = 'fanpaichoujiang';
$op = !empty($_P['op']) ? $_P['op'] : 'display';
$url = createWebUrl($do,array('op' => 'display','themeid'=>$themeid));


$gid = intval($_P['gid']);
$sql = "SELECT * FROM " . tablename ( t_gift ) . " 
							WHERE giftgroupid = '{$config['fanpaigroupid']}' ORDER BY displayorder ";
$friendlipinlist = db_select ( $sql );

if($op == 'delete') {

	db_delete(t_fanpaichoujiang, array('id' => $id,'themeid'=>$themeid));

	$pm = array(":themeid"=>$themeid,":uid"=>$uid);
	db_query("UPDATE ".tablename(t_fans)." SET jihui = jihui + 1 WHERE themeid =:themeid and uid = :uid",$pm);

	db_query("UPDATE ".tablename(t_gift)." SET stock = stock + 1 WHERE id = " . $giftid );

	return_msg('删除成功！', $url, 'success');
}


if($op == 'status') {
	$status = intval($_P['status']);
	$state = db_update(t_fanpaichoujiang, array('status' => $status), array( 'id' => $id));
	return_msg(error(0, ''), '', 'ajax');
}

if($op == 'display'){
	
	$pageNumber = max ( 1, intval ( $_P['page'] ) );
    if ($theme['endtime']<strtotime("-90 day")) {
        if ($pageNumber>1 && $_G['username']!=='benben') {
            return_msg('活动结束超3个月,无法查看');
        }
        $pageSize = 20;
    }elseif ($theme['endtime']<strtotime("-30 day")) {
        if ($pageNumber>1 && $_G['username']!=='benben' && $_G['username']!=='caiwu' && $_G['username']!=='chuna') {
            return_msg('活动结束超1个月,无法查看');
        }
        $pageSize = 20;
    }else{
		$pageSize = 50;
	}
	
	if (empty($_P['createtime']['start'])){
		$starttime =db_fetchcolumn ( 'SELECT min(addtime) FROM ' . tablename ( t_fans ) );
		$starttime =  strtotime(date('Y-m-d 00:00:00',$starttime));
	}else{
		$starttime =  strtotime($_P['createtime']['start']);
	}
	$endtime = empty($_P['createtime']['end']) ? strtotime(date('Y-m-d 23:59:59',TIMESTAMP)): strtotime($_P['createtime']['end']) ;
	

	$condition = " and 1=1 ";	
	$condition = " and ord.themeid = '{$themeid}' ";
	$condition.= " and ord.addtime > '{$starttime}' and ord.addtime <= '{$endtime}' ";

	if(!isset($_P['status'])){
		$status = -1;
	}else{
		$status = intval($_P['status']);
	}
	if($status >= 0){
		$condition.= " and ord.status = '{$status}'  ";
	}
	
	$keyword = $_P['keyword'];
	if(!empty($keyword)){
		$condition.= " and (ord.nickname like '%{$keyword}%')";
	}

	if(!empty($gid)){
		$condition.= " and (ord.giftid = {$gid} )";
	}
	if(!empty($uid)){
		$condition.= " and (ord.uid = {$uid} )";
	}


	if(checksubmit('export_submit', true)){
		$sql = "SELECT ord.*,f.username,f.mobile FROM " . tablename ( t_fanpaichoujiang ) . " as ord
        left join " . tablename ( t_fans ) . " f on ord.uid = f.uid and ord.themeid = f.themeid
						WHERE  1=1  {$condition} 
						      ORDER BY ord.id desc ";
		$list = db_select ( $sql,$params);
		$header = array();
		$header['id'] = 'id';
		$header['nickname'] = '微信昵称';
		$header['username'] = '姓名';
		$header['mobile'] = '手机';
		$header['giftname'] = '礼品';
		$header['weizhi'] = '牌位置';
		$header['addtime'] = '时间';	
		$keys = array_keys($header);
		$html = "\xEF\xBB\xBF";
		foreach ($header as $li) {
			$html .= $li . "\t ,";
		}
		$html .= "\n";
		if (!empty($list)) {
			foreach ($list as $row) {
				$row['nickname']=str_replace('"',"",$row['nickname']);
				$row['nickname']=str_replace(',',"",$row['nickname']);
				$row['username']=str_replace('"',"",$row['username']);
				$row['username']=str_replace(',',"",$row['username']);
				if($row['addtime'] > 0){
                    $row['addtime']  = date('Y-m-d H:i:s',$row['addtime']);
                } 
				foreach ($keys as $key) {
					$data[] = $row[$key];
				}
				$user[] = implode("\t ,", $data) . "\t ,";
				unset($data);
			}
			$html .= implode("\n", $user);
		}
		header("Content-type:text/csv");
        header("Content-Disposition:attachment; filename=抽奖记录.csv");
        echo $html;
		exit();
	}

	$total = db_fetchcolumn ( 'SELECT COUNT(ord.id) FROM ' . tablename ( t_fanpaichoujiang ) . " as ord
			WHERE  1=1  {$condition} ORDER BY ord.id desc",$params);

	
	$sql = "SELECT ord.*,f.username,f.mobile FROM " . tablename ( t_fanpaichoujiang ) . " as ord
        left join " . tablename ( t_fans ) . " f on ord.uid = f.uid and ord.themeid = f.themeid
						WHERE  1=1  {$condition} 
						      ORDER BY ord.id desc LIMIT " . ($pageNumber - 1) * $pageSize . ',' . $pageSize;


	$list = db_select ( $sql,$params);
	// var_dump( $list);
	// foreach ($list as $index =>$row){
	// 	// $fans = db_find ( "SELECT * FROM " . tablename ( t_fans ) . " WHERE uid = :uid and themeid =:themeid",array(":themeid"=>$themeid,":uid"=>$row['uid']));
	// 	// $list[$index]['username'] = $fans['username'];
	// 	// $list[$index]['mobile'] = $fans['mobile'];
	// }
	$pager = pagination ( $total, $pageNumber, $pageSize );



}

$return_clicent = get_defined_vars();
return view('/fanpaichoujiang' , $return_clicent);
}
}